// pages/index/index.js
const app = getApp();
const time = require('../../utils/time.js');
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageRoot: app.globalData.imageRoot,
    background: [
      // {
      //   name: 'banner1',
      //   url: 'http://localhost/dev-api/profile/upload/2023/03/04/img12_20230304152815A002.jpg',
      // },
      // {
      //   name: 'banner2',
      //   url: 'http://localhost/dev-api/profile/upload/2023/03/04/img11_20230304152755A001.jpg',
      // }, {
      //   name: 'banner3',
      //   url: 'http://localhost/dev-api/profile/upload/2023/03/04/03_20230304142515A001.jpg',
      // }
    ],
    
    def: 'https://img.alicdn.com/tps/i3/T1QYOyXqRaXXaY1rfd-32-32.gif',
    windowWidth: '',
    btn_chek: 0,
    indicatorDots: true,
    duration: 500,
    InfoShow: false,
    loading:true,
    infoScroll: [{
        id: 1,
        text: '100%真实房源'
      },
      {
        id: 2,
        text: '优惠价格/极速购房'
      },
      {
        id: 3,
        text: '品质房源/放心购房'
      },
    ],
    userInfo: false,
    phone: false,
    user:{},
    body_btn: [{
        id: 1,
        name: '我要放盘',
        img: 'https://api.yipaiju.com/resources/images/wawa/index_1.png',
        url: '../../subpackages/pages/listing/listing'
      },
      {
        id: 2,
        name: '我要好房',
        img: 'https://api.yipaiju.com/resources/images/wawa/indexIcon-3.png',
        url: '../../subpackages/pages/room/room'
      },
      {
        id: 3,
        name: '增值服务',
        img: 'https://api.yipaiju.com/resources/images/wawa/indexIcon-1.png',
        url: '../../subpackages/pages/serving/serving'
      },
      {
        id: 4,
        name: '地图找房',
        img: 'https://api.yipaiju.com/resources/images/wawa/indexIcon-7.png',
        // url:'../map/map'
        url: '../newMap/newMap'
      },
      {
        id: 5,
        name: '邀请好友',
        img: 'https://api.yipaiju.com/resources/images/wawa/indexIcon-6.png',
        url: '../invipage/invipage'
      },
      {
        id: 6,
        name: '自由购房',
        img: 'https://api.yipaiju.com/resources/images/wawa/indexIcon-2.png',
        url: 'lists'
      },
      {
        id: 7,
        name: '心选好房',
        img: 'https://api.yipaiju.com/resources/images/wawa/indexIcon-5.png',
        url: '../../subpackages/pages/card/card'
      },
      {
        id: 8,
        name: '税费计算',
        img: 'https://api.yipaiju.com/resources/images/wawa/jsq.png',
        url: '../../subpackages/pages/taxation/taxation'
      },
      {
        id: 9,
        name: '企业联系',
        img: 'https://api.yipaiju.com/resources/images/wawa/indexIcon-4.png',
        url: '../contact/contact'
      },
      {
        id: 10,
        name: '数据中心',
        img: 'https://api.yipaiju.com/resources/images/wawa/index_5.png',
        url: '../../subpackages/pages/newDataCenter/dataCenter'
      },
    ],
    login: false,
    marquee: 0, //每次移动X坐标
    windowWidth: 0, //小程序宽度
    maxScroll: 0, //文本移动至最左侧宽度及文本宽度
    searchValue: '',
    userme: '',
    locationstatus: 1,
    chek: 0,
    list: []
  },
  onShareAppMessage() {
    return {
      title: 'scroll-view',
      path: 'page/component/pages/scroll-view/scroll-view'
    }
  },
  handleContact(e) { //跳转到客服
  },
  scroll_house(data) {
    var that = this;
    if (that.data.longitude && that.data.latitude) {
      data.longitude = that.data.longitude
      data.latitude = that.data.latitude
    } else {
      data.longitude = app.globalData.longitude
      data.latitude = app.globalData.latitude
    }

    getApp().ports.apicitydsec({ data }).then((res11) => {
      var statuss = ['待审核', '待上架', '出售中', '已出售'];
      data.page_size = 5;
      data.orderings = 'browse'
      data.city = res11.data.city
      // data.status = 2;
      getApp().ports.apiqb({
        data: data
      }).then((res) => {
        var res = res.data;
        res.forEach(item => {
          item.distance = util.getDistance(that.data.latitude, that.data.longitude, item.latitude, item.longitude);
          // item.type==1?'优选':'折扣'
          if (item.type == 1) {
            switch (item.stage) {
              case '变卖':
                item.stage = '秒杀'
                break;
              case '一拍':
                item.stage = '一轮'
                break;
              case '二拍':
                item.stage = '二轮'
                break;
            }
            item.tags = [{
              name: item.builtUpAreaSquareCentimeter + '㎡'
            }, {
              name: item.discountRate + '折'
            }, {
              name: item.stage || ''
            }]
            item.time = app.timeFormat(item.endTime)
            item.marketPriceYuan = Math.floor((item.marketPriceYuan / 10000));
            item.priceYuan = Math.floor((item.priceYuan / 10000));
            item.estimatePriceYuan = Math.floor((item.estimatePriceYuan / 10000));
            item.dealPrice = Math.floor((item.dealPrice / 10000));
            item.url = "../details/details?status=0&&id=" + item.id
          } else {
            item.time = app.timeFormat(item.uploadTime);
            item.status = statuss[parseInt(item.status)];
            if (item.tagsstr) {
              let tags = [];
              item.tagsstr.split(",").forEach(item => {
                tags.push({name: item})
              })
              item.tags = tags;
            }
            item.url = "../details/details?status=1&&id=" + item.id
          }
        })
        that.setData({
          scroll_list: res
        })
      }).catch(() => {
        console.error('出啥错了？');
      });



    }).catch(() => {
      console.error('获取省市区失败！')
    })

  },
  api(data) { //请求
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    if (that.data.longitude && that.data.latitude) {
      data.longitude = that.data.longitude
      data.latitude = that.data.latitude
    } else {
      data.longitude = app.globalData.longitude
      data.latitude = app.globalData.latitude
    }
    var statuss = ['待审核', '待上架', '出售中', '已出售'];
    // data.status = 2;
    data.page_size = 8
    // 按关注度排序  这个不用传 这个按位置排序的
    // data.orderings = 'browse'
    getApp().ports.apiqb({
      data: data
    }).then((res) => {
      var res = res.data;
      res.forEach(item => {
        item.distance = util.getDistance(that.data.latitude, that.data.longitude, item.latitude, item.longitude);
        if (item.type == 1) {
          switch (item.stage) {
            case '变卖':
              item.stage = '秒杀'
              break;
            case '一拍':
              item.stage = '一轮'
              break;
            case '二拍':
              item.stage = '二轮'
              break;
          }
          item.tags = [{
            name: item.builtUpAreaSquareCentimeter + '㎡'
          }, {
            name: item.discountRate + '折'
          }, {
            name: item.stage
          }]
          item.time = (app.timeFormat(item.startTime)||'') + '-' + (app.timeFormat(item.endTime)||'')
          item.marketPriceYuan = Math.floor((item.marketPriceYuan / 10000));
          item.estimatePriceYuan = Math.floor((item.estimatePriceYuan / 10000));
          item.priceYuan = Math.floor((item.priceYuan / 10000));
          item.dealPrice = Math.floor((item.dealPrice / 10000));
          item.url = "../details/details?status=0&&id=" + item.id;
        } else {
          item.time = item.uploadTime;
          item.status = statuss[parseInt(item.status)];
          if (item.tagsstr) {
            let tags = [];
            item.tagsstr.split(",").forEach(item => {
              tags.push({name: item})
            })
            item.tags = tags;
          }
          item.url = "../details/details?status=1&&id=" + item.id
        }
      })

      that.setData({
        list: res,
        loading:false
      })
      wx.hideLoading({
        success: (res) => {
          // that.onShowImg()
        },
      })
    }).catch(() => {
      console.error('出啥错了？');
    });
  },
  getPhoneNumber(e) { //页面授权
    let that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let data = {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        appid: app.globalData.appid,
      }
      getApp().ports.api54({
        data
      }).then((res) => {
        // wx.setStorageSync('phone', res.data)
        // that.setData({
        //   phone: false
        // })

        that.data.user.phone_is_verified = true
        that.setData({
          phone: false,
          user: that.data.user
        })

      }).catch(() => {
        console.error("授权电话号码解密失败！")
      })
    } else {
      return
    }
  },
  getUserInfo(e) { //页面授权
    var that = this;
    if (e.detail.errMsg == "getUserInfo:ok") {
      let data = {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        appid: app.globalData.appid,
      }
      getApp().ports.loginInfo({
        data
      }).then((res) => {
        wx.setStorageSync('userInfo', res.data)
        that.setData({
          userInfo: false
        })
      }).catch(() => {
        console.error('出啥错了？');
      });
    } else {
      return
    }
  },
  location() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        let latitude = res.latitude //纬度
        let longitude = res.longitude //经度
        let data = {
          latitude: latitude,
          longitude: longitude
        }
        Object.assign(that.data, {
          latitude: latitude,
          longitude: longitude
        });
        app.globalData.latitude = latitude
        app.globalData.longitude = longitude
        that.api(data);
        that.scroll_house(data)
      },
      fail(error) {
        let data = {}
        that.setData({
          locationstatus: 2
        })
        that.api(data)
        that.scroll_house(data)
      }
    })
  },
  banner() {
    let that = this;
    app.ports.banner({}).then((res) => {
      var res = res.data;
      let background = (res.length <= 0 ? that.data.background : res)
      that.setData({
        background: background
      })
      // console.log(res)
    }).catch((res) => {
      console.error('banner图请求失败')
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  userme() {
    let that = this;
    app.ports.getInfo({}).then((res) => {
      let phone = false;
      // if (res.data.phone_is_verified == null || res.data.phone_is_verified == ''){
      //   phone = true;
      // }
      res.data.nickname = ''
      that.setData({
        userme: res.data,
        phone: false
      })
      // if (!res.data.ext1) {
      //   that.showNicknameDialog();
      // }
      // if (res.data.phone_is_verified) that.setData({
      //   phone: false
      // }); //判断是否授权电话号码
      // if (res.data.avatar_url) that.setData({
      //   userInfo: false
      // });
    }).catch(() => {
      console.error("获取自身信息出错！")
    })
  },
  onLoad: async function (options) {
    console.log("index>>>options>>>>>", options);

    // app.ports.wechatTest({data: options}).then(res => {}).catch(() => {})

    // wx.showToast({
    //   title: JSON.stringify(options),
    //   icon: 'none',
    //   duration: 6500
    // })
    var that = this;
    // if (new Date(time.timeHandle(null, 0)) >= new Date('2021-04-29')){
    //   console.log(12312)
    // }
      //绑定邀请
      // app.globalData.indexUrl = this;
    if (options.scene) { //扫码进入
      let params = {};
      decodeURIComponent(options.scene).split("&").forEach(item => {
        let itemParam = item.split("=");
        params[itemParam[0]] = itemParam[1];
      })
      // let invitestId = params.userId || params.id;
      let invitestId = params.userId;
      if (params.type) {
        var json = {
          pk: params.id
        }
        switch (params.type) {
          case 1:
            app.ports.khfpqy({
              data: {},
              json
            }).then(res => {}).catch(() => {
              console.error('创建失败')
            })
            break;
          case 2:
            // console.log(json)
            app.ports.khzkqy({
              data: {},
              json
            }).then((res) => {
              console.log(res)
            }).catch(() => {
              console.error('创建失败')
            })
            break;
          case 3:
            app.ports.khfanpqy({
              data: {},
              json
            }).then(res => {}).catch(() => {
              console.error('创建失败')
            })
            break;
        }
      }
      let data = {
        user_pk: invitestId
      }
      console.log(data)
      app.ports.apiinvites({
        data
      }).then(res => {}).catch(() => {
        console.error('建立邀请关系失败！')
      })


      // let parms = {
      //   key: options.scene
      // }
      // app.ports.apiqrdata({
      //   parms
      // }).then(res => {
      //   let invitestId = JSON.parse(res.data).userid || JSON.parse(res.data).id
      //   if (JSON.parse(res.data).type) {
      //     var json = {
      //       pk: JSON.parse(res.data).id
      //     }
      //     switch (JSON.parse(res.data).type) {
      //       case 1:
      //         app.ports.khfpqy({
      //           data: {},
      //           json
      //         }).then(res => {}).catch(() => {
      //           console.error('创建失败')
      //         })
      //         break;
      //       case 2:
      //         // console.log(json)
      //         app.ports.khzkqy({
      //           data: {},
      //           json
      //         }).then((res) => {
      //           console.log(res)
      //         }).catch(() => {
      //           console.error('创建失败')
      //         })
      //         break;
      //       case 3:
      //         app.ports.khfanpqy({
      //           data: {},
      //           json
      //         }).then(res => {}).catch(() => {
      //           console.error('创建失败')
      //         })
      //         break;
      //     }
      //   }
      //   let data = {
      //     user_pk: invitestId
      //   }
      //   console.log(data)
      //   app.ports.apiinvites({
      //     data
      //   }).then(res => {}).catch(() => {
      //     console.error('建立邀请关系失败！')
      //   })
      // }).catch(() => {
      //   console.error('拉取启动参数！')
      // })
    }
    if (options.share) { //分享进入页面
      // if(!shareId) return false
      //share=3b7cd9ce-ab20-490d-8f6c-2fe31550e94c
      let data = {
        user_pk: options.share
      }
      app.ports.apiinvites({
        data
      }).then(res => {
        // wx.showToast({
        //   title: '绑定邀请成功!',
        //   icon: 'success',
        //   duration: 4000
        // })
      }).catch(() => {
        console.error('建立邀请关系失败！')
      })
    }

    that.location()
    // await getApp().ports.getInfo({}).then(async (res) => {
    //   if (res.data.nickname) { //判断是否授用户信息
    //     app.globalData.login = false
    //   } else {
    //     app.globalData.login = true
    //   }
    // }).catch(() => {
    //   console.error("获取自身信息出错！")
    // })
    that.setData({
      edition: app.globalData.edition,
      myStyle: app.globalData.color,
      // login: app.globalData.login
    });
    that.userme();
  },

  onShowImg() {
    let list = this.data.list // 获取原数据
    for (let i in this.data.list) {
      wx.createIntersectionObserver().relativeToViewport({
        bottom: 20
      }).observe('.item-' + i, (ret) => {
        if (ret.intersectionRatio > 0) {
          list[i].show = true
        }
        this.setData({ // 更新数据
          list
        })
      })
    }
  },
  onClosePhone() {
    this.setData({
      PhoneShow: false
    })
  },
  onCloseInfo() {
    this.setData({
      InfoShow: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    var that = this;
    that.getTabBar().init();
    that.banner();
    
    // await getApp().ports.getInfo({}).then(async (res) => {
    //   if (res.data.nickname) { //判断是否授用户信息
    //     app.globalData.login = false
    //   } else {
    //     app.globalData.login = true
    //     // wx.navigateTo({
    //     //   url: '../login/login',
    //     // })
    //   }
    // }).catch(() => {
    //   console.error("获取自身信息出错！")
    // })
    // that.setData({
    //   login: app.globalData.login
    // })
  },
  // onButtonClick  (status) {
  //   const actions = new Map([
  //     [1, ['1', '2','3']],
  //     [2, ['4', '5','6','7']],
  //     ['default', ['other', 'Index']],
  //   ])
  //   let action = actions.get(status) || actions.get('default')
  //   console.log(action[0])
  //   console.log(action[1])
  // },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.api({})
    that.banner()
    that.scroll_house({})
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this;
    var shareId = wx.getStorageSync('userId');
    // if (res.from === 'button') {}
    return {
      title: '去邀请更多小伙伴一起加入吧',
      path: 'pages/index/index?share=' + shareId,
      success: function (res) {}
    }
  },
  // scrolltxt: function () {
  //   var that = this;
  //   var d = that.data;

  //   var interval = setInterval(function () {
  //     var next = d.marquee - 1; //每次移动距离
  //     if (next < 0 && Math.abs(next) > d.maxScroll) {
  //       next = d.windowWidth;
  //       clearInterval(interval);
  //       that.scrolltxt();
  //     }
  //     that.setData({
  //       marquee: next
  //     });
  //   }, 80);
  // },
  search: function (e) {
    var that = this;
    var data = {
      latitude: that.data.latitude,
      longitude: that.data.longitude,
      title: e.detail
    }
    this.api(data)
  },
  navTo: function (e) {
    var url = e.currentTarget.dataset.url
    console.log(url)
    if (url == "lists") {
      wx.switchTab({
        url: '../lists/lists',
      });
    } else {
      wx.navigateTo({
        url: url,
      })
    }
  },
  item_swiper: function (e) {
    var that = this;
    that.setData({
      chek: e.detail.current
    })
  },
  swiper_btn(e) {
    var that = this;
    that.setData({
      btn_chek: e.detail.current
    })
  },


})